<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/1/11
 * 描述:
 */

namespace app\result\chat;

use app\model\chat\ChatConversationsSummary;
use app\model\chat\ChatMessages;
use app\model\goods\Goods;
use app\model\order\Order;
use app\model\order\OrderGoods;
use app\model\user\User;
use app\result\BaseResult;
use app\result\UploadResult;
use GatewayClient\Gateway;

class ChatResult extends BaseResult
{
    public function ready($user_id, $args = []): array
    {
        $goods_id = $args['goods_id'] ?? 0;
        $order_sn = $args['order_sn'] ?? '';
        $kefu_id = $args['kefu_id'] ?? 10000;
        $conversation_id = $args['conversation_id'] ?? 0;
        $targetUser = [
            'id' => $kefu_id,
            'avatar' => 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png',
            'nickname' => '平台客服'
        ];
        $data = [
            'socketUrl' => config('worker.socketUrl'),
            'maxReconnectTimes' => config('worker.maxReconnectTimes'),
            'online' => true,
            'targetUser' => $targetUser
        ];
        if ($conversation_id) {
            $summary = (new ChatConversationsSummary())->data_get([
                ['conversation_id', '=', $conversation_id],
                ['user_id', '<>', $user_id]
            ], '*', 'id desc');

            if ($summary) {
                //判断是否为客服
                if ($summary['user_id'] == 10000) {
                    $data['targetUser']['id'] = $summary['user_id'];
                    try {
                        $data['online'] = Gateway::isUidOnline($summary['user_id']);
                    } catch (\Exception $e) {
                        $data['online'] = false;
                        bs_log($e->getMessage(), 'gateway', 'err-worker.log');
                    }
                }
            }
        }
        if ($goods_id) {
            $goodsInfo = (new Goods())->data_get([
                ['goods_id', '=', $goods_id]
            ], 'goods_id,goods_name,goods_image,goods_price');
            $data['goodsInfo'] = $goodsInfo;
        }
        if ($order_sn) {
            $orderInfo = (new Order())->data_get([
                ['order_sn', '=', $order_sn]
            ], 'order_sn,order_id,pay_status,order_status,order_pay_price,pay_price');
            if ($orderInfo) {
                $orderInfo['goods_image'] = (new OrderGoods())->get_value(['order_id' => $orderInfo['order_id']], 'goods_image');
            }
            $data['orderInfo'] = $orderInfo;
        }
        return self::success_return('success', $data);
    }

    //留言
    public function msg($args = []): array
    {
        return self::success_return('保存成功');
    }

    public function history_list($user_id, $args = []): array
    {
        $conversation_id = $args['conversation_id'] ?? 0;
        if (!$conversation_id) {
            return self::success_return('success', [
                'list' => []
            ]);
        }
        $page = $args['page'] ?? 1;
        $pageSize = $args['pageSize'] ?? 50;
        $where = [
            'conversation_id' => $conversation_id,
        ];
        $model = new ChatMessages();
        $data = $model->data_list($where, '*', 'id desc', $page, $pageSize)?->toArray();
        //标记已读
        (new ChatConversationsSummary())->data_update([
            'conversation_id' => $conversation_id,
            'user_id' => $user_id,
        ], ['read_time' => time(), 'unread_count' => 0]);
        if ($data) {
            $modelUser = new User();
            foreach ($data as &$item) {
                $item['type'] = $item['message_type'];
                $item['time'] = ChatResult::format_lastTime($item['created_at']);
                $item['isSelf'] = $item['sender_id'] == $user_id;
                if ($item['isSelf']) {
                    $item['avatar'] = $modelUser->where(['user_id' => $item['sender_id']])->value('avatar');
                } else {
                    $item['avatar'] = 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png';
                }
                $item['file_info'] = null;
                if ($item['type'] == 'file') {
                    $item['file_info'] = UploadResult::get_file_info($item['content']);
                } elseif ($item['type'] == 'goods') {
                    $item['goods_info'] = json_decode($item['content'], true);
                } elseif ($item['type'] == 'order') {
                    $item['order_info'] = json_decode($item['content'], true);
                }
            }
            unset($item);
            //再按id顺序
            usort($data, function ($a, $b) {
                return $a['id'] - $b['id'];
            });
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }

    //会话列表
    public function conversation_list($user_id, $args = []): array
    {
        $page = $args['page'] ?? 1;
        $pageSize = $args['pageSize'] ?? 50;
        $where = [
            'a.user_id' => $user_id,
            'a.is_deleted' => 0,
        ];
        $field = 'a.user_id,a.conversation_id,a.latest_message_id,a.latest_message_time,a.unread_count as unreadCount';
        $field .= ',b.user_ids';
        $modelSummary = new ChatConversationsSummary();
        $data = $modelSummary->alias('a')
            ->join('chat_conversations b', 'a.conversation_id = b.conversation_id', 'left')
            ->where($where)
            ->page($page, $pageSize)
            ->order('a.id desc')
            ->field($field)
            ->select()
            ->toArray();
        if ($data) {
            //相关用户信息
            $user_ids = explode(',', join(',', array_column($data, 'user_ids')));
            $user_ids = array_unique($user_ids);
            $modelUser = new User();
            $modelMessage = new ChatMessages();
            $allUsers = $modelUser->data_list_nopage([['user_id', 'in', $user_ids]], 'user_id,avatar,username,account');
            $allMessages = $modelMessage->data_list_nopage([['id', 'in', array_unique(array_column($data, 'latest_message_id'))]]);
            if ($allUsers) {
                $allUsers = array_column($allUsers, null, 'user_id');
            }
            if ($allMessages) {
                $allMessages = array_column($allMessages, null, 'id');
            }
            $kefuAvatar = 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png';
            $defaultAvatar = 'https://source.alipay168.cn/skushop/a14a2eb8bedcc7d07ee58a4440e9e460.png';
            foreach ($data as &$item) {
                $item['avatar'] = $allUsers[$item['user_id']]['avatar'] ?? $defaultAvatar;
                $message = $allMessages[$item['latest_message_id']];
                $targetUserId = $message['sender_id'] == $user_id ? $message['receiver_id'] : $message['sender_id'];
                if ($message['sender_id'] == $user_id) {
                    $item['nickname'] = $allUsers[$message['receiver_id']]['username'] ?? '';
                } else {
                    $item['nickname'] = $allUsers[$message['sender_id']]['username'] ?? '';
                }
                if ($targetUserId == 10000) {
                    $item['avatar'] = $kefuAvatar;
                    $item['nickname'] = '平台客服';
                }
                $item['lastTime'] = self::format_lastTime($message['created_at']);
                $item['lastMessage'] = $this->format_lastMessage($message['message_type'], $message['content']);

                if ($message['sender_id'] == $user_id) {
                    $item['unreadCount'] = 0;
                }

            }
            unset($item);
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }

    public static function format_lastTime($lastTime): string
    {
        $now = time();
        $lastTime = strtotime($lastTime);
        $diff = $now - $lastTime;
        if ($diff < 60) {
            return '刚刚';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . '分钟前';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . '小时前';
        } elseif ($diff < 2592000) {
            return floor($diff / 86400) . '天前';
        } else if ($diff < 31536000) {
            return date('m月d日', $lastTime);
        } else {
            return date('Y年m月d日', $lastTime);
        }
    }

    //格式化消息
    public static function format_lastMessage($messageType, $content): string
    {
        return match ($messageType) {
            'text' => mb_strlen($content) > 30 ? (mb_substr($content, 0, 30) . '...') : $content,
            'image' => '[图片]',
            'file' => '[文件]',
            'order' => '[订单信息]',
            'goods' => '[商品信息]',
            default => '[其它]'
        };
    }
}
